import { createStore } from 'vuex'
import { getLocalStorage, setLocalStorage } from '../uitls/storage'
const setLocalCartList = (state) => {
  const { cartList } = state
  const cartListString = setLocalStorage('cartList', cartList)
}
export default createStore({
  state: {
    // 商铺id
    // 商品id
    // 商品详情及购物数量
    cartList: getLocalStorage('cartList') ?? {}
  },
  mutations: {
    changeCartList(state, payload) {
      const { shopId, productId, productInfo, type } = payload
      let shopInfo = state.cartList[shopId] || { shopName: '', productList: {} }
      let product = shopInfo.productList[productId]
      if (!product) {
        productInfo.count = 0
        product = productInfo
      }
      if (type === 'plus') {
        product.count += 1
      } else {
        product.count -= 1
      }
      if (product.count) product.check = true
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    changeCartItemChecked(state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId].productList[productId]
      product.check = !product.check
      setLocalCartList(state)
    },
    cleanCartProducts(state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    },
    setCartItemsChecked(state, payload) {
      const { shopId } = payload
      const productList = state.cartList[shopId].productList
      if (productList) {
        for (let key in productList) {
          const product = productList[key]
          product.check = true
        }
      }
      setLocalCartList(state)
    }
  },
  actions: {

  },
  modules: {

  }
})